package nl.hva.three2learn.controller;

import javax.servlet.http.HttpSession;

import nl.hva.three2learn.controller.event.EventFactory;
import nl.hva.three2learn.controller.event.IEventListener;
import nl.hva.three2learn.model.Event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public abstract class BaseController {

	@Autowired
	private IEventListener eventListener;
	
	@Autowired
	private EventFactory eventFactory;
	
	protected final void flash(HttpSession session, String message) {
		session.setAttribute("_flash", message);
	}
	
	/**
	 * Returns <code>true</code> if the user is currently logged in.
	 * @return <code>true</code> if the user is logged in, <code>false</code> otherwise
	 */
	protected final boolean isUserLoggedIn() {		
		SecurityContext context = SecurityContextHolder.getContext();
		return context.getAuthentication() != null;
	}
	
	/**
	 * Returns the event factory that is used to create events.
	 * @return
	 */
	protected final EventFactory getEventFactory() {
		return eventFactory;
	}
	
	/**
	 * Dispatches the given event to the event listener. Use
	 * the event factory to create events.
	 * @param e The event to dispatch
	 * @see #getEventFactory()
	 */
	protected final void dispatchEvent(Event e) {
		eventListener.notiftyEvent(e);
	}
}
